<!-- 用户聊天 -->
<template>
  <div class="user-chat-container">
    <van-sticky :offset-top="0">
      <van-nav-bar left-arrow
                   @touchmove.prevent>
        <template #right>
          <van-icon name="friends-o"
                    size="18"
                    color="inherit"
                    @click="navigatorPrivateInfo" />
        </template>
        <template #left>
          <van-icon name="arrow-left"
                    size="18"
                    color="inherit"
                    @click="goBack" />
        </template>
        <template #title>
          <span>{{toRealName}} </span>
          <van-tag v-if="toOnline"
                   round
                   type="success"
                   class="online-tag">在线</van-tag>
          <van-tag v-else
                   round
                   class="online-tag"
                   color="#969799">离线</van-tag>
        </template>
      </van-nav-bar>
    </van-sticky>

    <div class="chat-window-editor">
      <!-- 这里横划线和驼峰都可以，最终会转成驼峰 -->
      <chat-window :chat-records="chatRecords"
                   :to-identity="toIdentity"></chat-window>
      <!-- 聊天编辑器 -->
      <van-sticky :offset-bottom="0"
                  position="bottom"
                  id="stickyBottom">
        <chat-editor :to="toIdentity"
                     :isCaller0="isCaller"
                     :showOverlay0="showOverlay"
                     :singleType="singleType"
                     @sendMsg="sendMsg"
                     @changeChatHeight="changeChatContentHeight"
                     @touchmove.prevent></chat-editor>
      </van-sticky>
    </div>

  </div>
</template>

<script>
import { Toast } from 'vant';
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import ChatEditor from "../../components/ChatEditor.vue";
import ChatWindow from "../../components/ChatWindow.vue";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { ChatEditor, ChatWindow },
  data () {
    //这里存放数据
    return {
      // 对方名称
      toRealName: '',
      // 对方在线状态
      toOnline: false,
      // 对方唯一标识
      toIdentity: '',
      // 聊天消息集合
      chatRecords: [],
      isCaller: true,
      showOverlay: false,
      // 信令类型
      singleType: ''
    };
  },
  //方法集合
  methods: {
    // 初始化数据
    init (type) {
      var that = this;


      // 获取对方名称，在线状态等
      that.$http
        .get(that.$reqPrefix.user + "/im/users/chat", {}).then(res => {
          that.toRealName = res.data[0].realName;
          that.toOnline = res.data[0].online === 1 ? true : false;
        }).catch(err => {
          Toast.fail(err.data.message)
        });
      // 组装消息记录
      //消息id
      // msgId: "1",
      // //用户id
      // userId: "1",
      // //用户昵称
      // nickName: "转功能三",
      // //用户头像url
      // avatarUrl: "https://img01.yzcdn.cn/vant/cat.jpeg",
      // //聊天内容类型：文本，表情，语音，视频，图片，文件......
      // chatContentType: "1",
      // //聊天内容
      // chatContent:
      //   "你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面",
      // //发送或接受时间
      // sendMsgTime: "2021-08-19 16:44:32",
      // //是否是我发送的
      // fromMe: 1,
      that.$http
        .get(that.$reqPrefix.im + "/im/users/" + this.toIdentity + "/chat-records", {}).then(res => {
          res.data.forEach(chatRecord => {
            var chatContent = null;
            // 判断聊天内容类型
            if (chatRecord.chatContentType === 0) {
              chatContent = chatRecord.chatContent;
            } else if (chatRecord.chatContentType === 2) {
              chatContent = JSON.parse(chatRecord.chatContent);
            }
            that.chatRecords.push({
              ...chatRecord,
              chatContent: chatContent,
              //是否展示气泡
              popover: {
                showPopover: false,
                actions: [
                  { text: "删除" },
                  { text: "添加" },
                ],
              },
            });

          });
          that.$emitter.on('onmessage', that.onmessage);
        }).catch(err => {
          Toast.fail(err.data.message);
        });
    },
    goBack () {
      // 返回上一层
      this.$router.go(-1);
    },
    // 跳转到私聊的信息页面
    navigatorPrivateInfo () {
      this.$router.push({ path: "/info/private", query: { id: "123456" } });
    },
    // 子组件回传数据给父组件，进行追加
    sendMsg (chatData) {
      var that = this;
      this.$http
        .get(that.$reqPrefix.user + "/users/" + this.$socket.config.identity, {}).then(res => {
          that.chatRecords.push({
            //消息id,这里先固定
            msgId: chatData.msgId.toString(),
            //用户id
            userId: that.$socket.config.identity,
            //用户昵称
            nickName: res.data.realName,
            //用户头像url
            avatarUrl: res.data.avatar,
            //聊天内容类型
            chatContentType: chatData.contentType,
            //聊天内容
            chatContent: chatData.chatContent,
            //发送或接受时间
            sendMsgTime: new Date().getTime(),
            //是否是我发送的
            fromMe: 1,
            //是否展示气泡
            popover: {
              showPopover: false,
              actions: [
                { text: "删除" },
                { text: "添加" },
              ],
            },
          });
        }).catch(err => {
          Toast.fail(err.data.message);
        });

    },


    //总线回调函数，得到的消息数据传递给子组件
    onmessage: function (data) {
      if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_P_CHAT) {
        var identity = data.message.getFrom();
        var contentType = data.message.getContentType();
        var jsonContent = null;
        if (contentType === SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT) {
          jsonContent = data.message.getContent();
        } else if (contentType === SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.ATTACHMENT_CONTENT) {
          jsonContent = JSON.parse(data.message.getContent())
        }
        // 判断数组中是否包含现有的数据，如果包含只是简单的更新，否则添加新数据
        if (identity === this.toIdentity) {
          var that = this;
          this.$http
            .get(that.$reqPrefix.user + "/users/" + this.toIdentity, {}).then(res => {
              // 追加一条记录到集合中
              this.chatRecords.push({
                //消息id,这里先固定
                msgId: data.messageId,
                //用户id
                userId: this.toIdentity,
                //用户昵称
                nickName: res.data.realName,
                //用户头像url
                avatarUrl: res.data.avatar,
                //聊天内容类型
                chatContentType: contentType,
                //聊天内容
                chatContent: jsonContent,
                //发送或接受时间
                sendMsgTime: data.message.getCreateTime(),
                //是否是我发送的
                fromMe: 0,
                //是否展示气泡
                popover: {
                  showPopover: false,
                  actions: [
                    { text: "删除" },
                    { text: "添加" },
                  ],
                },
              });
            }).catch(err => { Toast.fail(err.data.message) });

        }
      }

    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    var that = this;

    // 获取webrtc
    this.singleType = that.$route.params.webrtc;

    // 从路由参数中获取对方的聊天唯一标识
    that.toIdentity = that.$route.params.identity;
    that.init();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  //生命周期 - 创建之前
  beforeCreate () { },
  //生命周期 - 挂载之前
  beforeMount () { },
  //生命周期 - 更新之前
  beforeUpdate () { },
  //生命周期 - 更新之后
  updated () { },
  //生命周期 - 销毁之前
  beforeUnmount () { },
  //生命周期 - 销毁完成
  unmounted () {//销毁监听
    this.$emitter.off('onmessage', this.onmessage);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () { },
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.user-chat-container {
  height: 19.5rem;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
}
.online-tag {
  font-size: 2px;
}
.chat-window-editor {
  //flex-grow: 1;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-content: space-between;
  justify-content: space-between;
}
</style>
